package multithreading;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/3 18:01
 * <p>
 * 银行有一个账户。
 * 有两个储户分别向同一个账户存3000元，每次存1000，存3次。每次存完打印账户余额。
 * 问题:该程序是否有安全问题，如果有，如何解决?
 * 【提示】
 * 1、明确哪些代码是多线程运行代码，须写入run()方法
 * 2、明确什么是共享数据。
 * 3、明确多线程运行代码中哪些语句是操作共享数据的。
 */
class Account{
    private int money;

    public Account(int money) {
        this.money = money;
    }

    /**
     * 存钱
     * @param money
     */
    public synchronized void saveMoney(int money) {
        if (money > 0) {
            this.money += money;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "账户剩余" + this.money);
        }
    }
}

class Customer implements Runnable {

    private Account account;

    public Customer(Account account) {
        this.account = account;
    }

    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            account.saveMoney(1000);
        }
    }
}

public class Practice {
    public static void main(String[] args) {
        Account account = new Account(0);
        Customer customer = new Customer(account);
        Customer customer1 = new Customer(account);
        Thread thread = new Thread(customer);
        Thread thread1 = new Thread(customer1);
        thread.setName("用户1线程");
        thread1.setName("用户2线程");
        thread.start();
        thread1.start();
    }
}
